<?php

	//start the session
	session_start();
	$response;
	$userId;
	$firstName;
	//call the login function
	login();

	//get username & passord
	function login() {
		global $response, $userId, $firstName;

		$userName = $_GET["userName"];
		//create an array of userName, password pairs (key/element)
		$users = array(
				"meuniern" => array(
					"password" => "meuniern",
					"email" => "nathan.meunier@rocky.edu"
				),
				"urbanskia" => array(
					"password" => "urbanskia",
					"email" => "alex.urbanski@rocky.edu"
				)
			);

		$response = array(
			'success' => false
		);

		$userId = '';

#		$emailFile = fopen("../userInfo/email.txt", 'r') or die("cannot open user file");
		//check if password for username in users array matches passed in password`
		if(validateUser($userName)){
			$response['success'] = true;

			//if the username is valid, set the session variable
			$_SESSION['userName'] = $userName;
			if(getFirstName($userId)){
				$_SESSION['firstName'] = $firstName;
			}
		}

		echo json_encode($response);
		
	}

	function validateUser($userName){
		global $response, $userId;

		$userFile = fopen("../userInfo/users.txt", 'r') or die("cannot open user file");

		while(($buffer = fgets($userFile)) != false){
			$user = explode(",", $buffer);
			if($userName == $user[0]){
				$userId = $user[1];
				if(validPassword($password)){
					$response['validUser'] = true;
					fclose($userFile);
					return true;
				}
			}
		}

		return false;
	}

	function getFirstName($userId){
		global $firstName, $response;

		$userInfoFile = fopen("../userInfo/info.txt", 'r') or die("can't open user info file");;

		while(($buffer = fgets($userInfoFile)) != false){
			$user = explode(",", $buffer);
			if(trim($userId) == trim($user[2]) && $user[0] != null){
				$firstName = $user[0];
				return true;
			}
		}

		return false;
	}

	function validPassword($userId){
		global $response, $userId;

		$password = $_GET["password"];

		$passwordFile = fopen("../userInfo/passwords.txt", 'r') or die("cannot open user file");

		while(($buffer = fgets($passwordFile)) != false){
			$user = explode(",", $buffer);
			if($userId == $user[1]){
				if($password == $user[0]){
					$response['validPassword'] = true;
					return true;
				}
			}
		}
		return false;
	}

?>
